//views/orders/PendingShipmentOrders.vue
<template>
  <div class="pending-shipment-orders">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>待发货订单管理</span>
          <div class="right">
            <el-button type="primary" @click="handleBatchShipment" :disabled="!selectedOrders.length">
              批量发货
            </el-button>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              :shortcuts="dateShortcuts"
              class="date-picker"
            />
            <el-input
              v-model="searchForm.keywords"
              placeholder="订单号/收货人/手机号"
              class="search-input"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="orderList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column type="expand">
          <template #default="props">
            <div class="goods-info">
              <div v-for="item in props.row.goodsList" :key="item.id" class="goods-item">
                <el-image
                  :src="item.image"
                  :preview-src-list="[item.image]"
                  fit="cover"
                  class="goods-image"
                />
                <div class="goods-detail">
                  <p class="goods-name">{{ item.name }}</p>
                  <p class="goods-spec">规格：{{ item.specs }}</p>
                  <p class="goods-price">
                    单价：¥{{ item.price }} × {{ item.quantity }}
                  </p>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="orderNo" label="订单号" width="180" />

        <el-table-column label="收货信息" width="200">
          <template #default="scope">
            <p>{{ scope.row.receiverName }}</p>
            <p>{{ scope.row.receiverPhone }}</p>
            <p class="address-text">{{ scope.row.receiverAddress }}</p>
          </template>
        </el-table-column>

        <el-table-column label="支付信息" width="150">
          <template #default="scope">
            <p>支付方式：{{ scope.row.paymentMethod }}</p>
            <p>支付时间：{{ scope.row.payTime }}</p>
            <p class="total-amount">实付：¥{{ scope.row.totalAmount }}</p>
          </template>
        </el-table-column>

        <el-table-column label="商品信息" width="150">
          <template #default="scope">
            <p>商品数量：{{ getTotalQuantity(scope.row.goodsList) }}</p>
            <p>商品种类：{{ scope.row.goodsList.length }}</p>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="下单时间" width="180" />

        <el-table-column prop="payTime" label="支付时间" width="180" />

        <el-table-column prop="status" label="状态" width="100">
          <template #default>
            <el-tag type="warning">待发货</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleViewDetails(scope.row)"
            >
              订单详情
            </el-button>
            <el-button
              type="success"
              link
              @click="handleShipment(scope.row)"
            >
              发货
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleCancelOrder(scope.row)"
            >
              取消订单
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 发货对话框 -->
    <el-dialog
      v-model="shipmentDialogVisible"
      :title="isMultiple ? '批量发货' : '订单发货'"
      width="600px"
    >
      <el-form :model="shipmentForm" label-width="100px">
        <el-form-item label="物流公司" required>
          <el-select v-model="shipmentForm.company" placeholder="请选择物流公司">
            <el-option
              v-for="item in shippingCompanies"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <template v-if="!isMultiple">
          <el-form-item label="运单号" required>
            <el-input v-model="shipmentForm.trackingNo" placeholder="请输入运单号" />
          </el-form-item>
        </template>

        <template v-else>
          <div v-for="order in selectedOrders" :key="order.id" class="batch-order-item">
            <p class="order-info">
              订单号：{{ order.orderNo }}
              <span class="receiver">收货人：{{ order.receiverName }}</span>
            </p>
            <el-form-item
              :label="'运单号'"
              :prop="'trackingNos.' + order.id"
              required
            >
              <el-input
                v-model="shipmentForm.trackingNos[order.id]"
                placeholder="请输入运单号"
              />
            </el-form-item>
          </div>
        </template>

        <el-form-item label="备注">
          <el-input
            v-model="shipmentForm.remark"
            type="textarea"
            rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shipmentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShipment">
            确认发货
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailsVisible"
      title="订单详情"
      width="800px"
      destroy-on-close
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">
          {{ currentOrder.orderNo }}
        </el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag type="warning">待发货</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="下单时间">
          {{ currentOrder.createTime }}
        </el-descriptions-item>
        <el-descriptions-item label="支付时间">
          {{ currentOrder.payTime }}
        </el-descriptions-item>
        <el-descriptions-item label="收货人">
          {{ currentOrder.receiverName }}
        </el-descriptions-item>
        <el-descriptions-item label="联系电话">
          {{ currentOrder.receiverPhone }}
        </el-descriptions-item>
        <el-descriptions-item label="收货地址" :span="2">
          {{ currentOrder.receiverAddress }}
        </el-descriptions-item>
        <el-descriptions-item label="支付方式">
          {{ currentOrder.paymentMethod }}
        </el-descriptions-item>
        <el-descriptions-item label="支付金额">
          ¥{{ currentOrder.totalAmount }}
        </el-descriptions-item>
      </el-descriptions>

      <div class="goods-list">
        <h4>商品信息</h4>
        <el-table :data="currentOrder.goodsList" border>
          <el-table-column prop="name" label="商品名称" />
          <el-table-column prop="specs" label="规格" width="150" />
          <el-table-column prop="price" label="单价" width="100">
            <template #default="scope">
              ¥{{ scope.row.price }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column label="小计" width="100">
            <template #default="scope">
              ¥{{ scope.row.price * scope.row.quantity }}
            </template>
          </el-table-column>
        </el-table>

        <div class="amount-info">
          <p>商品总额：¥{{ currentOrder.goodsAmount }}</p>
          <p>运费：¥{{ currentOrder.shippingFee }}</p>
          <p class="total">实付金额：¥{{ currentOrder.totalAmount }}</p>
        </div>
      </div>
    </el-dialog>

    <!-- 取消订单对话框 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="取消订单"
      width="500px"
    >
      <el-form :model="cancelForm" label-width="100px">
        <el-form-item label="取消原因" required>
          <el-select v-model="cancelForm.reason" placeholder="请选择取消原因">
            <el-option
              v-for="item in cancelReasons"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注说明">
          <el-input
            v-model="cancelForm.remark"
            type="textarea"
            rows="3"
            placeholder="请输入备注说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancelOrder">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 物流公司选项
const shippingCompanies = [
  { value: 'SF', label: '顺丰速运' },
  { value: 'YTO', label: '圆通速递' },
  { value: 'ZTO', label: '中通快递' },
  { value: 'STO', label: '申通快递' },
  { value: 'YD', label: '韵达快递' },
  { value: 'EMS', label: 'EMS' }
]

// 取消订单原因选项
const cancelReasons = [
  { value: 1, label: '缺货' },
  { value: 2, label: '价格变动' },
  { value: 3, label: '客户要求取消' },
  { value: 4, label: '信息填写错误' },
  { value: 5, label: '其他原因' }
]

// 状态变量
const loading = ref(false)
const orderList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dateRange = ref([])
const searchForm = reactive({
  keywords: '',
  startDate: '',
  endDate: ''
})

const selectedOrders = ref([])
const detailsVisible = ref(false)
const currentOrder = ref({})
const shipmentDialogVisible = ref(false)
const cancelDialogVisible = ref(false)

// 发货表单
const shipmentForm = reactive({
  company: '',
  trackingNo: '',
  trackingNos: {},
  remark: ''
})

// 取消订单表单
const cancelForm = reactive({
  reason: '',
  remark: ''
})

// 是否批量发货
const isMultiple = computed(() => selectedOrders.value.length > 1)

// 计算商品总数量
const getTotalQuantity = (goodsList) => {
  return goodsList.reduce((sum, item) => sum + item.quantity, 0)
}

// 表格选择
const handleSelectionChange = (selection) => {
  selectedOrders.value = selection
}
// 继续 PendingShipmentOrders.vue 的 script setup 部分

// 获取订单列表
const getOrderList = async () => {
  loading.value = true
  try {
    // 这里替换为实际的API调用
    const res = await fetch('/api/orders/pending-shipment', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        page: currentPage.value,
        pageSize: pageSize.value,
        ...searchForm
      })
    })
    const data = await res.json()
    if (data.code === 0) {
      orderList.value = data.data.list
      total.value = data.data.total
    } else {
      ElMessage.error(data.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 查看订单详情
const handleViewDetails = (row) => {
  currentOrder.value = row
  detailsVisible.value = true
}

// 单个订单发货
const handleShipment = (row) => {
  selectedOrders.value = [row]
  shipmentForm.company = ''
  shipmentForm.trackingNo = ''
  shipmentForm.trackingNos = {}
  shipmentForm.remark = ''
  shipmentDialogVisible.value = true
}

// 批量发货
const handleBatchShipment = () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请选择要发货的订单')
    return
  }

  shipmentForm.company = ''
  shipmentForm.trackingNo = ''
  shipmentForm.trackingNos = {}
  shipmentForm.remark = ''
  shipmentDialogVisible.value = true
}

// 确认发货
const confirmShipment = async () => {
  if (!shipmentForm.company) {
    ElMessage.warning('请选择物流公司')
    return
  }

  // 验证运单号
  if (isMultiple.value) {
    const missingTrackingNo = selectedOrders.value.some(
      order => !shipmentForm.trackingNos[order.id]
    )
    if (missingTrackingNo) {
      ElMessage.warning('请填写所有订单的运单号')
      return
    }
  } else {
    if (!shipmentForm.trackingNo) {
      ElMessage.warning('请填写运单号')
      return
    }
  }

  try {
    if (isMultiple.value) {
      // 批量发货
      const shipmentData = selectedOrders.value.map(order => ({
        orderId: order.id,
        shippingCompany: shipmentForm.company,
        trackingNo: shipmentForm.trackingNos[order.id],
        remark: shipmentForm.remark
      }))

      const res = await fetch('/api/orders/batch-shipment', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(shipmentData)
      })
      const data = await res.json()
      if (data.code === 0) {
        ElMessage.success('批量发货成功')
        shipmentDialogVisible.value = false
        getOrderList()
      } else {
        ElMessage.error(data.message || '批量发货失败')
      }
    } else {
      // 单个订单发货
      const res = await fetch(`/api/orders/${selectedOrders.value[0].id}/shipment`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          shippingCompany: shipmentForm.company,
          trackingNo: shipmentForm.trackingNo,
          remark: shipmentForm.remark
        })
      })
      const data = await res.json()
      if (data.code === 0) {
        ElMessage.success('发货成功')
        shipmentDialogVisible.value = false
        getOrderList()
      } else {
        ElMessage.error(data.message || '发货失败')
      }
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('发货操作失败')
  }
}

// 取消订单
const handleCancelOrder = (row) => {
  currentOrder.value = row
  cancelForm.reason = ''
  cancelForm.remark = ''
  cancelDialogVisible.value = true
}

// 确认取消订单
const confirmCancelOrder = async () => {
  if (!cancelForm.reason) {
    ElMessage.warning('请选择取消原因')
    return
  }

  try {
    const res = await fetch(`/api/orders/${currentOrder.value.id}/cancel`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(cancelForm)
    })
    const data = await res.json()
    if (data.code === 0) {
      ElMessage.success('订单已取消')
      cancelDialogVisible.value = false
      getOrderList()
    } else {
      ElMessage.error(data.message || '取消订单失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('取消订单失败')
  }
}

// 搜索相关
const handleSearch = () => {
  if (dateRange.value) {
    searchForm.startDate = dateRange.value[0]
    searchForm.endDate = dateRange.value[1]
  } else {
    searchForm.startDate = ''
    searchForm.endDate = ''
  }
  currentPage.value = 1
  getOrderList()
}

const resetSearch = () => {
  searchForm.keywords = ''
  dateRange.value = []
  searchForm.startDate = ''
  searchForm.endDate = ''
  currentPage.value = 1
  getOrderList()
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  getOrderList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getOrderList()
}

// 初始化
onMounted(() => {
  getOrderList()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right {
  display: flex;
  gap: 10px;
}

.date-picker {
  width: 350px;
}

.search-input {
  width: 200px;
}

.goods-info {
  padding: 20px;
}

.goods-item {
  display: flex;
  gap: 20px;
  margin-bottom: 10px;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.goods-image {
  width: 80px;
  height: 80px;
}

.goods-detail {
  flex: 1;
}

.goods-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.goods-spec {
  color: #666;
  font-size: 14px;
  margin-bottom: 5px;
}

.goods-price {
  color: #f56c6c;
}

.address-text {
  color: #666;
  font-size: 13px;
}

.total-amount {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.batch-order-item {
  border-bottom: 1px solid #eee;
  padding: 10px 0;
}

.order-info {
  margin-bottom: 10px;
  color: #666;
}

.receiver {
  margin-left: 20px;
}

.amount-info {
  margin-top: 20px;
  text-align: right;
}

.amount-info p {
  margin: 5px 0;
}

.total {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}
</style>
